package com.whj.apidriver.service.impl;

import com.alibaba.nacos.api.utils.StringUtils;
import com.whj.apidriver.remote.ServiceDriverUserClient;
import com.whj.apidriver.remote.ServiceVerificationCodeClient;
import com.whj.apidriver.service.VerificationCodeService;
import com.whj.internalcommon.constant.CommonStatusEnum;
import com.whj.internalcommon.constant.DriverCarConstants;
import com.whj.internalcommon.constant.IdentityConstant;
import com.whj.internalcommon.constant.TokenTypeConstants;
import com.whj.internalcommon.dto.ResponseResult;
import com.whj.internalcommon.request.VerificationCodeDTO;
import com.whj.internalcommon.response.DriverUserExistsResponse;
import com.whj.internalcommon.response.NumberCodeResponse;
import com.whj.internalcommon.response.TokenResponse;
import com.whj.internalcommon.utils.JwtUtils;
import com.whj.internalcommon.utils.RedisTokenKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: wanghaijun
 * @Date: 2023/1/14 - 01 - 14 - 15:06 
 * @Description: com.whj.apidriver.service.impl
 */

@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Autowired
    private ServiceDriverUserClient serviceDriverUserClient;

    @Autowired
    private ServiceVerificationCodeClient serviceVerificationCodeClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public ResponseResult checkAndSentVerificationCode(String driverPhone) {

        //查询service-driver-user，该手机号是否存在
        ResponseResult<DriverUserExistsResponse> driverUser = serviceDriverUserClient.getDriverUser(driverPhone);
        Integer ifExists = driverUser.getData().getIfExists();
        if(ifExists== DriverCarConstants.DRIVER_NOT_EXISTS){
            return ResponseResult.fail(CommonStatusEnum.DRIVER_NOT_EXISTS.getCode(),CommonStatusEnum.DRIVER_NOT_EXISTS.getValue(),"");
        }
        log.info(driverPhone+"的司机存在");

        //获取验证码
        ResponseResult<NumberCodeResponse> responseResult = serviceVerificationCodeClient.numberCode(6);
        NumberCodeResponse numberCodeResponse = responseResult.getData();
        int numberCode = numberCodeResponse.getNumberCode();
        log.info("司机验证码："+numberCode);
        //调用第三方服务发送验证码

        //存入redis
        String keyByPhone = RedisTokenKeyUtils.keyByPhone(driverPhone, IdentityConstant.DRIVER_IDENTITY);
        stringRedisTemplate.opsForValue().set(keyByPhone,numberCode+"",2, TimeUnit.MINUTES);

        return ResponseResult.success("");
    }


    /**
     * 验证乘客发送的验证码，并判断用户是否存在，存在返回token，不存在，注册并返回token
     *
     * @param driverPhone   手机号
     * @param verificationCode 验证码
     * @return
     */
    @Override
    public ResponseResult checkCode(String driverPhone, String verificationCode) {
        //根据手机号，去redis读取验证码

        //生成key       注：当有拷贝的欲望时可以考虑是否抽象为方法
        //String key =verificationCodePrefix+passengerPhone;
        String key = RedisTokenKeyUtils.keyByPhone(driverPhone, IdentityConstant.DRIVER_IDENTITY);

        //根据key 获取value
        String redisKey = stringRedisTemplate.opsForValue().get(key);

        //校验验证码
        //验证码过期
        if (StringUtils.isBlank(redisKey)) {
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_OVERDUE.getCode(), CommonStatusEnum.VERIFICATION_CODE_OVERDUE.getValue());
        }
        //验证码错误
        if (!verificationCode.trim().equals(redisKey.trim())) {
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(), CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        }

        //颁发令牌
        String accessToken = JwtUtils.generatorToken(driverPhone, IdentityConstant.DRIVER_IDENTITY, TokenTypeConstants.ACCESS_TOKEN_TYPE);
        String refreshToken = JwtUtils.generatorToken(driverPhone, IdentityConstant.DRIVER_IDENTITY, TokenTypeConstants.REFRESH_TOKEN_TYPE);

        //将token保存到redis中
        String accessTokenKey = RedisTokenKeyUtils.keyByTokenMsg(driverPhone, IdentityConstant.DRIVER_IDENTITY, TokenTypeConstants.ACCESS_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 30, TimeUnit.DAYS);
        //refreshToken比accessToken晚过期一天，保证accessToken过期后refreshToken有效
        String refreshTokenKey = RedisTokenKeyUtils.keyByTokenMsg(driverPhone, IdentityConstant.DRIVER_IDENTITY, TokenTypeConstants.REFRESH_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 31, TimeUnit.DAYS);

        //响应
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);

        return ResponseResult.success(tokenResponse);
    }
}
